package com.graduation.lastproject.controller.admin.AdminHighActive;


import com.graduation.lastproject.entity.*;

import com.graduation.lastproject.service.admin.AdminHighActive.AdminHighService;
import com.graduation.lastproject.util.export.exportUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.rmi.server.ExportException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/adminHigh")
public class AdminHighController {
    private Logger logger= LoggerFactory.getLogger(AdminHighController.class);
    @Autowired
    private AdminHighService adminHighService;
    @Value("${spring.Commodityupload.destination}")
    private String destination;


    @RequestMapping(value = "{page}")
    public Object topages(@PathVariable String page, HttpServletRequest request){
        //@PathVariable 映射url地址占位符的参数 到方法参数中；
        String pages="admin/"+page;
        return pages;
    }


    //获取用户数据
    @RequestMapping(value = "/getUserListPage"/*,method = RequestMethod.POST*/)
    @ResponseBody
    public PageMore<User> getUserListPage(User user, HttpServletRequest request) {

        PageMore<User> pageHelper = new PageMore<User>();
        // 统计总记录数
        Integer total = adminHighService.getTotal(user);
        pageHelper.setTotal(total);
        // 查询当前页实体对象
        List<User> list = adminHighService.getUserListPage(user);
        pageHelper.setRows(list);
        return pageHelper;
    }

    //根据用户id对用户拉黑
    @RequestMapping(value = "lahe",method = RequestMethod.POST)
    @ResponseBody
    public Object userActiv(HttpServletRequest request){
        Map<String,Object> result = new HashMap<>() ;
        Map<String,Object> map =parmeters(request);
        //shasha的我咋不晓得在js直接处理好再传值 傻哦
        String stringBuffer="";
        if (map.get("value1")!=null&&!"".equals(map.get("value1").toString())&&!"null".equals(map.get("value1").toString()))
        {
            stringBuffer+=map.get("value1").toString()+" ";
        }
        if (map.get("value2")!=null&&!"".equals(map.get("value2").toString())&&!"null".equals(map.get("value2").toString()))
        {
            stringBuffer+=map.get("value2").toString();
        }
        map.put("reason",stringBuffer);
        map.put("state","1");
        map.put("id",map.get("userId").toString());
        int i=adminHighService.updataUserInfo(map);
        result.put("msg",i==1 ? "拉黑成功" : "拉黑失败");
        return result;
    }

    //获取商家信息
    @RequestMapping(value = "/getBusinessListPage" /*,method = RequestMethod.POST*/)
    @ResponseBody
    public PageMore<Business> getBusinessListPage(Business business){
        PageMore<Business> page=new PageMore<>() ;
        //查询商家数据总数
        Integer total=adminHighService.getBusinessTotal(business);
        page.setTotal(total);
        //查询所有商家信息
        List<Business> businesses=adminHighService.getBusinessListPage(business);
        page.setRows(businesses);
        return page;
    }

    //根据商家id对商家拉黑 以及对商家酒店信息下架 更改酒店表state
    @RequestMapping(value = "/businesslahe")
    @ResponseBody
    public Object businessActive(HttpServletRequest request){
       Map<String,Object> result=new HashMap<>();
       Map<String,Object> map=parmeters(request);
       int i=adminHighService.updataBusinessInfo(map);
       result.put("msg",i==1 ? "操作成功" : "操作失败");
       return result;
    }

    //get business_hotel info
    @RequestMapping(value = "/getBusinessInfoListPage")
    @ResponseBody
    public PageMore<HotelInfo> getBusinessInfoListPage(HotelInfo hotelInfo){
        PageMore<HotelInfo> hotelInfoPageMore=new PageMore<>() ;
        //get total
        Integer total=adminHighService.getBusinessInfoTotal(hotelInfo);
        hotelInfoPageMore.setTotal(total);
        //get hotel list
        List<HotelInfo> hotelInfos=adminHighService.getBusinessInfoListPage(hotelInfo);
        hotelInfoPageMore.setRows(hotelInfos);
        return  hotelInfoPageMore;
    }

    //pass business_hotel Info
    @RequestMapping(value = "passHotel" ,method = RequestMethod.POST)
    @ResponseBody
    public Object passHotel(HttpServletRequest request){
        Map<String,Object> result=new HashMap<>() ;
        String id=request.getParameter("id"); //酒店主键id
        int i=adminHighService.passHotel(id);
        result.put("msg",i==1 ? "操作成功" : "操作失败");
        return result;
    }

    //return business_hotel Info
    @RequestMapping(value = "businessInfoRetutn",method = RequestMethod.POST)
    @ResponseBody
    public Object businessInfoRetutn(HttpServletRequest request){
        Map<String,Object> result=new HashMap<>() ;
        Map<String,Object> map=parmeters(request);
        int i=adminHighService.returnHotel(map);
        result.put("msg",i==1 ? "操作成功" : "操作失败");
        return result;
    }

    /*获取所有订单*/
    @RequestMapping("/getBookorderListPage")
    @ResponseBody
    public PageMore<Bookorder> bookorderLstPage(Bookorder bookorder){
        PageMore<Bookorder> pageMore=new PageMore<>();
        /*获取订单总数*/
        int total =adminHighService.getOrderTotal(bookorder);
        pageMore.setTotal(total);
        /*获取所有订单信息*/
        List<Bookorder> list=adminHighService.getOrderInfoListPage(bookorder);
        pageMore.setRows(list);
        return pageMore;
    }

    /*删除订单*/
    @RequestMapping(value = "/deleteBookorder" ,method = RequestMethod.POST)
    @ResponseBody
    public Object deleteBookorder(String orderId){
        Map<String,Object> result=new HashMap<>() ;
        int i=adminHighService.deleteBookorderById(orderId);
        result.put("msg" ,i ==1 ? "删除成功" : "删除失败");
        return result;
    }

    /*获取所有评论*/
    @RequestMapping(value = "/getReviewListPage")
    @ResponseBody
    public PageMore<Review> getReviewListPage(Review review){
         PageMore<Review> pageMore=new PageMore<>();
         /*获取评论总数*/
         int total=adminHighService.getReviewTotal(review);
         pageMore.setTotal(total);
         /*获取所有评论信息*/
         List<Review> list=adminHighService.getReviewInfoListPage(review);
         pageMore.setRows(list);
         return  pageMore;
    }

    /*删除评论*/
    @RequestMapping(value = "/deleteReview" , method = RequestMethod.POST)
    @ResponseBody
    public Object deleteReview(String reviewId){
        Map<String,Object> result=new HashMap<>() ;
        int i=adminHighService.deleteReviewById(reviewId);
        result.put("msg" ,i ==1 ? "删除成功" : "删除失败");
        return result;
    }


    /*商品信息保存*/
    @RequestMapping(value = "/addCommodity" ,method = RequestMethod.POST)
    @ResponseBody
    public Object addCommodity(HttpServletRequest request ,MultipartFile file) throws Exception{
        Map<String,Object> result=new HashMap<>() ;
        String commodityDes=request.getParameter("commodityDes");
        String reserve=request.getParameter("reserve");
        String commodityIntegral=request.getParameter("commodityIntegral");
        String commodityState=request.getParameter("commodityState");
        // 获取上传的文件名称，并结合存放路径，构建新的文件名称
        String filename = file.getOriginalFilename();
        String fileExtName = String.valueOf(System.currentTimeMillis());
        String filepathName=fileExtName+"_"+filename;
        File filepath = new File(destination, filepathName);
        // 判断路径是否存在，不存在则新创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        // 将上传文件保存到目标文件目录
        file.transferTo(filepath);
        String path="D:\\\\file\\\\commodityPicInfo"+"\\\\"+filepathName;
        String realPath=path.replace("\\\\", "/");
        Map<String,Object> info=new HashMap<>();
        info.put("picLocation",realPath);
        info.put("commodityDes", commodityDes);
        info.put("reserve",reserve);
        info.put("commodityIntegral",commodityIntegral);
        info.put("commodityState",commodityState);
        int i=adminHighService.insertComInfo(info);
        result.put("msg", i==1 ? "添加成功":"添加失败" );
        return result;
    }

     /*查询所有商品信息*/
    @RequestMapping(value = "/getCommodityListPage")
    @ResponseBody
    public PageMore<Commodity>  getCommodityListPage(Commodity commodity){
        PageMore<Commodity> pageMore=new PageMore<>() ;
        /*获取商品总数*/
        int total=adminHighService.getComTotal(commodity);
        pageMore.setTotal(total);
        /*获取所有商品信息*/
        List<Commodity> list=adminHighService.getComInfoListPage(commodity);
        pageMore.setRows(list);
        return pageMore;
    }

    /*商品信息修改*/
    @RequestMapping(value = "/editCommodity", method=RequestMethod.POST)
    @ResponseBody
    public Object editCommodity(HttpServletRequest request,MultipartFile file) throws IOException {
        Map<String,Object> result=new HashMap<>();
        Map<String,Object>  map=parmeters(request);
        String oldpic=map.get("newLoc").toString();
        /*截取上次文件名字*/
        logger.info(oldpic.indexOf("_")+"--"+oldpic.length());
        String recentFileName = oldpic.substring(oldpic.indexOf("_")+1, oldpic.length());
        /*file.getOriginalFilename()=="" 代表未更改*/
        if(recentFileName.equals(file.getOriginalFilename()) || file.getOriginalFilename()==""){
            /*如果图片还是与上次相符合，更新其他数据即可*/
            map.put("commodityPic","");
            int  j =adminHighService.updataExchangeInfo(map);
            result.put("msg", j==1 ? "修改成功" : "修改失败");
            return result;
        }else {
             /*如果图片还是与上次不符合，需要先保存图片 再删除之前保存对应的图片 更新其他数据即可*/
            // 获取上传的文件名称，并结合存放路径，构建新的文件名称
            String filename = file.getOriginalFilename();
            String fileExtName = String.valueOf(System.currentTimeMillis());
            String filepathName=fileExtName+"_"+filename;
            File filepath = new File(destination, filepathName);

            // 判断路径是否存在，不存在则新创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            // 将上传文件保存到目标文件目录
            file.transferTo(filepath);
            /*删除之前的图片  4.18不应该删 订单记录中用到*/
          /*  String oldpath="D:\\\\IdeaProjects\\\\lastproject\\\\src\\\\main\\\\resources"+oldpic.replace("/","\\\\");
            File file1=new File(oldpath);
            file1.delete();*/
            /*更新数据库数据*/
            String path="D:\\\\file\\\\commodityPicInfo"+"\\\\"+filepathName;
            String realPath=path.replace("\\\\", "/");
            map.put("commodityPic",realPath);
            int  j =adminHighService.updataExchangeInfo(map);
            result.put("msg", j==1 ? "修改成功" : "修改失败");
            return result;
        }
    }

    /*删除商品*/
    @RequestMapping(value = "/deitCommodity",method = RequestMethod.POST)
    @ResponseBody
    public Object deitCommodity(String deleteComId){
        Map<String,Object> result=new HashMap<>();
        int i=adminHighService.deleteComById(deleteComId);
        result.put("msg", i==1 ? "删除成功" : "删除失败");
        return  result;

    }

    /*查询所有用户兑换记录*/
    @RequestMapping(value = "getCommodityOrderListPage")
    @ResponseBody
    public PageMore<Commodityorder> getshopList(Commodityorder commodityorder){
        PageMore<Commodityorder> pageMore=new PageMore<>();
        /*查询总数*/
        int total=adminHighService.getShoporderTotal(commodityorder);
        pageMore.setTotal(total);
        /*查询所有记录信息*/
        List<Commodityorder> list=adminHighService.getShopInfoList(commodityorder);
        pageMore.setRows(list);
        return pageMore;
    }

    /*删除积分订单*/
    @RequestMapping(value = "/deleteIntegralorder" ,method = RequestMethod.POST)
    @ResponseBody
    public Object deleteIntegralorder(String commodity_orderId){
        Map<String,Object> result=new HashMap<>();
        int i=adminHighService.deleteIntegralorder(commodity_orderId);
        result.put("msg",i==1 ? "删除成功" : "删除失败");
        return result;
    }
    /*获取饼状图预定数量填充数据*/
    @RequestMapping(value = "/echartBing" ,method = RequestMethod.POST)
    @ResponseBody
    public Object getBooknum(){
        Map<String,Object> result= adminHighService.getBooknum();
        return result;
    }

    /*获取饼状图预定结果填充数据*/
    @RequestMapping(value = "/echartBingPrice" ,method = RequestMethod.POST)
    @ResponseBody
    public Object getBookprice(){
        Map<String,Object> result= adminHighService.getBookPrice();
        return result;
    }

    /*获取每个酒店收入总数*/
    @RequestMapping(value = "/getHotelLncomeListPage")
    @ResponseBody
    public PageMore<Hotelincome>  getHotelLncomeListPage(Hotelincome hotelincome){
        PageMore<Hotelincome> pageMore=new PageMore<>();
        /*获取总数*/
        int total = 0;
        try {
            total = adminHighService.getHotelpriceTotal(hotelincome);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        pageMore.setTotal(total);
        /*获取信息*/
        List<Hotelincome> list= null;
        try {
            list = adminHighService.getHotelpriceInfo(hotelincome);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        pageMore.setRows(list);
        return  pageMore;
    }

    /*酒店数据导出*/
    @RequestMapping(value = "/findOneTypeExport", method = RequestMethod.GET)
    public void findOneTypeExport(HttpServletRequest request, HttpServletResponse response) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("酒店结果信息");
        // 导出时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        buffer.append(format.format(new Date()));
        buffer.append(".xls");
        Map<String,Object> result = null;
        String inTime=request.getParameter("inTime") !=null ? request.getParameter("inTime") : "";
        try {
            result = adminHighService.getHotelpriceInfoExport(inTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        HSSFWorkbook wb = null;
        String[] title = {"酒店名称","酒店总收入","酒店支付宝号"};
        String sheetName="酒店收入统计";
        /*String starttime = request.getParameter("inTime");*/
        String starttime = "";
        String endtime = "";
        if(request.getParameter("inTime") != null ){
            starttime = request.getParameter("inTime");
        }
        wb = exportUtil.getHSSFWorkbook(sheetName,title, result,starttime,endtime);
        OutputStream os = null;
        try {
            this.setResponseHeader(request, response, buffer.toString());
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //request转map
    public Map<String,Object> parmeters(HttpServletRequest request){
        Map<String,Object>  parmete=new HashMap<>();
        if(request!=null){
            Enumeration<String> keys=request.getParameterNames();
            while (keys.hasMoreElements()){
                String key=keys.nextElement();
                try {
                    parmete.put(key,request.getParameter(key));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return parmete;
    }


    /**
     * 设置发送响应 文件导出编码问题
     *
     * @param request
     * @param response
     * @param fileName
     */
    public void setResponseHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String finalFileName = null;
            if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器
                finalFileName = URLEncoder.encode(fileName, "UTF8");
            } else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
                finalFileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                finalFileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
            }
            response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");// 这里设置一下让浏览器弹出下载提示框，而不是直接在浏览器中打开
            response.setContentType("application/vnd.ms-excel");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
